import dayjs from 'dayjs'
import RequireContext = __WebpackModuleApi.RequireContext

/**
 * @description 处理首字母大写 abc => Abc
 * @param str
 */
export const changeStr = (str: string) => {
  return str.charAt(0).toUpperCase() + str.slice(1)
}

export const apiUrl = () => {
  return 'http://cms-os.21ds.cn/'
}

export const domTitle = 'Dragon管理系统'

/**
 * @description 批量导入文件
 * @param {Object} context 上下文对象
 * @param {RegExp} reg 匹配规则
 * @returns {Object} 对象
 */
export const importAllModule = (context: RequireContext, reg = /\.vue$/) => {
  return context.keys().reduce((compObj: any, fileName) => {
    const compName = changeStr(fileName.replace(/^\.\//, '').replace(/\.\w+$/, ''))
    compObj[compName] = context(fileName).default || context(fileName)
    return compObj
  }, {})
}

/**
 * @description 异步导入组件
 * @param cateName 组件的分类
 * @param compName 组件名称
 * @return {Promise<*>}
 */
export const getAsyncComp = async (cateName, compName = 'index.vue') => {
  const result = await import(
    /* webpackChunkName: "[request]" */ `@/components/${cateName}/${compName}`
  )
  return result.default
}

/**
 * @description 随机生成颜色
 * @param {string} type
 * @return {string}
 */
export const randomColor = (type: 'rgb' | 'hex' | 'hsl'): string => {
  switch (type) {
    case 'rgb':
      return window.crypto.getRandomValues(new Uint8Array(3)).toString()
    case 'hex':
      return (
        '#' +
        Math.floor(Math.random() * 0xffffff)
          .toString(16)
          .padStart(6, `${Math.random() * 10}`)
      )
    case 'hsl':
      // 在25-95%范围内具有饱和度，在85-95%范围内具有亮度
      return [360 * Math.random(), 100 * Math.random() + '%', 100 * Math.random() + '%'].toString()
  }
}

/**
 * 复制文本
 * @param text
 */
export const copyText = (text: string) => {
  return new Promise((resolve, reject) => {
    const copyInput = document.createElement('input') //创建一个input框获取需要复制的文本内容
    copyInput.value = text
    document.body.appendChild(copyInput)
    copyInput.select()
    document.execCommand('copy')
    copyInput.remove()
    resolve(true)
  })
}

/**
 * @description 判断字符串是否是base64
 * @param {string} str
 */
export const isBase64 = (str: string): boolean => {
  if (str === '' || str.trim() === '') {
    return false
  }
  try {
    return btoa(atob(str)) == str
  } catch (err) {
    return false
  }
}
// 对象转JSON
export const toJSON = (obj) => {
  return JSON.stringify(obj, (key, value) => {
    switch (true) {
      case typeof value === 'undefined':
        return 'undefined'
      case typeof value === 'symbol':
        return value.toString()
      case typeof value === 'function':
        return value.toString()
      default:
        break
    }
    return value
  })
}

/***
 * @description 是否是生产环境
 */
export const IS_PROD = ['production', 'prod'].includes(process.env.NODE_ENV)
export const IS_DEV = ['development'].includes(process.env.NODE_ENV)

/***
 * @description 格式化日期
 * @param time
 */
export const formatTime = (time) => dayjs(time).format('YYYY-MM-DD HH:mm:ss')
export const getRangeDate = (range: number, type?: string) => {
  const formatDate = (time: any) => {
    // 格式化日期，获取今天的日期
    const Dates = new Date(time)
    const year: number = Dates.getFullYear()
    const month: any =
      Dates.getMonth() + 1 < 10 ? '0' + (Dates.getMonth() + 1) : Dates.getMonth() + 1
    const day: any = Dates.getDate() < 10 ? '0' + Dates.getDate() : Dates.getDate()
    return year + '-' + month + '-' + day
  }
  let changeDate: string
  changeDate = formatDate(new Date().getTime())
  const resultArr: Array<any> = []
  if (range) {
    if (type) {
      if (type === 'one') {
        changeDate = formatDate(new Date().getTime() + 1000 * 3600 * 24 * range)
        console.log(changeDate)
        return changeDate
      }
      if (type === 'more') {
        if (range < 0) {
          for (let i = Math.abs(range); i >= 0; i--) {
            resultArr.push(formatDate(new Date().getTime() + -1000 * 3600 * 24 * i))
            console.log(resultArr)
          }
        } else {
          for (let i = 1; i <= range; i++) {
            resultArr.push(formatDate(new Date().getTime() + 1000 * 3600 * 24 * i))
            console.log(resultArr)
          }
        }
        return resultArr
      }
    } else {
      changeDate = formatDate(new Date().getTime() + 1000 * 3600 * 24 * range)
      console.log(changeDate)
      return changeDate
    }
  }
  return changeDate
}

/**
 *  @description 将一维数组转成树形结构数据
 * @param items
 * @param id
 * @param link
 */
export const generateTree = (items, id = 0, link = 'parent') => {
  return items
    .filter((item) => item[link] == id)
    .map((item) => ({
      ...item,
      slots: { title: 'name' },
      children: generateTree(items, item.departmentid)
    }))
}

/***
 * @description 原生加密明文
 * @param {string} plaintext
 */
const encryption = (plaintext: string) =>
  isBase64(plaintext) ? plaintext : window.btoa(window.encodeURIComponent(plaintext))

/**
 * @description 原生解密
 * @param {string} ciphertext
 */
const decryption = (ciphertext: string) =>
  isBase64(ciphertext) ? window.decodeURIComponent(window.atob(ciphertext)) : ciphertext

import * as XLSX from 'xlsx'

export const inArray = (str, list) => {
  for (let index = 0; index < list.length; index++) {
    if (list[index] === str) {
      return true
    }
  }
}

// 自动计算col列宽
function auto_width(ws, data) {
  /*set worksheet max width per col*/
  const colWidth = data.map((row) =>
    row.map((val) => {
      /*if null/undefined*/
      if (val == null) {
        return { wch: 10 }
      } else if (val.toString().charCodeAt(0) > 255) {
        /*if chinese*/
        return { wch: val.toString().length * 2 }
      } else {
        return { wch: val.toString().length }
      }
    })
  )
  /*start in the first row*/
  const result = colWidth[0]
  for (let i = 1; i < colWidth.length; i++) {
    for (let j = 0; j < colWidth[i].length; j++) {
      if (result[j]['wch'] < colWidth[i][j]['wch']) {
        result[j]['wch'] = colWidth[i][j]['wch']
      }
    }
  }
  ws['!cols'] = result
}

// 将json数据转换成数组
function json_to_array(key, jsonData) {
  return jsonData.map((v) =>
    key.map((j) => {
      return v[j]
    })
  )
}

export const exportJsonToExcel = ({ header, data, key, title, filename, autoWidth }) => {
  const wb = XLSX.utils.book_new()
  const newData: any[] = []
  for (let i = 0; i < data.length; i++) {
    const element = data[i]
    const items = {}
    for (const keys in element) {
      if (inArray(keys, key)) {
        items[keys] = element[keys]
      }
    }
    newData.push(items) // Corrected this line
  }
  if (header) {
    newData.unshift(header)
  }
  if (title) {
    newData.unshift(title)
  }
  const ws = XLSX.utils.json_to_sheet(newData, {
    header: key,
    skipHeader: true
  })
  if (autoWidth) {
    const arr = json_to_array(key, newData)
    auto_width(ws, arr)
  }
  XLSX.utils.book_append_sheet(wb, ws, filename)
  XLSX.writeFile(wb, filename + '.xlsx')
}
